import md5 from './md5';

function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

function _getOrSetHistorySearch(_str){
  if(!!_str){
    var _history = wx.getStorageSync('searchHistory');
    var _historyArr;
    if(!!_history){
      _historyArr = _history.split(",")
      for(var i=0; i<_historyArr.length; i++){
        if(_historyArr[i] == _str) return;
      }
      if(_historyArr.length >= 4){
        _historyArr = _historyArr.splice(0,3);
      }
      _historyArr.splice(0,0, _str);
    }else{
      _historyArr = [];
      _historyArr.push(_str);
    } 
    wx.setStorageSync('searchHistory', _historyArr.join(","));
  }else{
    return wx.getStorageSync('searchHistory');
  }
}

function _formatCommonTime(_millisec){
  var _ret = "";
  if(_millisec != null && _millisec != undefined){
			var _time = new Date();
			_time.setTime(_millisec);//设置需要格式化的时间
			_ret = _time.getFullYear() + '-' + ((_time.getMonth() + 1)<10 ? "0":"") + (_time.getMonth() + 1) + '-' + (_time.getDate()<10 ? "0":"")+_time.getDate() + ' '
			 + _time.getHours()  + ':' + ((_time.getMinutes() < 10) ? "0":"") + _time.getMinutes();
		}
		return _ret;
}

function _formatCommonShortTime(_millisec){
  var _ret = "";
  if(_millisec != null && _millisec != undefined){
			var _time = new Date();
			_time.setTime(_millisec);//设置需要格式化的时间
			_ret = _time.getFullYear() + '-' + ((_time.getMonth() + 1)<10 ? "0":"") + (_time.getMonth() + 1) + '-' + (_time.getDate()<10 ? "0":"")+_time.getDate();
		}
		return _ret;
}


function _getIndexFromChinse(_str){
  var _map = {
    "零": 0,"一": 1,"二": 2,"三": 3,"四": 4,"五": 5,"六": 6,"七": 7,"八": 8,"九": 9,"十": 10,"百": 100
  }

  var _str = _str.replace(/第/g, "").replace(/条/g, "").replace(/([零一二三四五六七八九])/g, function($0, $1){
    return _map[$1];
  }).replace(/[十]/g, "*10+").replace(/[百]/g, "*100+");

  var _arrs = _str.split("+");
  var _result = 0;
  for(var i=0; i<_arrs.length; i++){
    var _tmpArr = _arrs[i].split("*");
    if(_tmpArr.length == 2){
      _result += (_tmpArr[0]||1)*_tmpArr[1];
    }else{
      _result += _tmpArr[0]*1;
    }
  }
  return _result;
}

function _genAjaxAuth(){
  var _staticStr = "ahshd1asdsfasfggas12312asdasf";
  var _time = new Date().getTime();
  if(_time%2 == 1){
    _staticStr = "sdasfadasda123asdagsdddsdssdd";
  }
  var _md5 = md5.md5(_time + _staticStr);

  return {
    timestamp: _time,
    token: _md5
  }
}

module.exports = {
  formatTime: formatTime,
  getOrSetHistorySearch: _getOrSetHistorySearch,
  formatCommonShortTime: _formatCommonShortTime,
  formatCommonTime: _formatCommonTime,
  getIndexFromChinse: _getIndexFromChinse,
  genAuth: _genAjaxAuth
}
